package com.hwd.gmall.oauth.contrroller;

import com.hwd.gmall.common.util.IpUtil;
import com.hwd.gmall.oauth.service.LoginService;
import com.hwd.gmall.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 自定义登录控制层
 *
 * @author 黄伟东/Victor
 * @date 2022/5/4 19:57
 */
@RestController
@RequestMapping(value = "/user/login")
public class LoginController {

    @Resource
    private LoginService loginService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private HttpServletRequest request;

    @Resource
    private HttpServletResponse response;

    private static final String TOKEN = "token";

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookiePath}")
    private String cookiePath;

    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @Value("${auth.ttl}")
    private Long ttl;

    /**
     * 自定义登录
     *
     * @param username 用户名
     * @param password 密码
     * @return com.hwd.gmall.oauth.util.AuthToken
     */
    @GetMapping
    public AuthToken login(@RequestParam("username")String username,@RequestParam("password") String password) {

        // 用户登录完成后，获取令牌
        AuthToken authToken = loginService.login(username, password);

        // 获取用户登录时的ip地址，把用户的令牌和ip地址绑定，并保存到redis中
        stringRedisTemplate.opsForValue().set(IpUtil.getIpAddress(request), authToken.getAccessToken(), ttl, TimeUnit.SECONDS);

        // 把token放到cookie中
        response.addCookie(getCookie(authToken));

        return authToken;
    }

    /**
     * 设置cookie
     *
     * @param authToken token
     * @return javax.servlet.http.Cookie
     */
    private Cookie getCookie(AuthToken authToken) {
        Cookie cookie = new Cookie(TOKEN, authToken.getAccessToken());
        cookie.setDomain(cookieDomain);
        cookie.setPath(cookiePath);
        cookie.setMaxAge(cookieMaxAge);
        return cookie;
    }
}
